extends CharacterBody2D

# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")

@onready var anim = get_node("AnimatedSprite2D") as AnimatedSprite2D

var chase = false
var SPEED = 50


func _ready():
	anim.play("Idle")

func _physics_process(delta):
	velocity.y += gravity * delta
	
	if chase :
		var player = $"../../Player/Player" as CharacterBody2D
		var direction = (player.global_position - self.global_position).normalized()
		#print(direction)
		if direction.x > 0:
			anim.flip_h = true
		else:
			anim.flip_h = false
		velocity.x = SPEED * direction.x
		if anim.animation != "Death":
			anim.play("Jump")
	else :
		velocity.x = 0
		if anim.animation != "Death":
			anim.play("Idle")

	#var direction = 
		
	move_and_slide()

func _on_area_check_player_body_entered(body):
	if body.name == "Player":
		chase = true
	
	#print("进来了")

func _on_area_check_player_body_exited(body):
	print("出去了")
	if body.name == "Player":
		chase = false


func _on_area_check_top_body_entered(body):
	if body.name == "Player":
		_death()

func _death():
		print("踩到我了")
		chase = false
		anim.play("Death")
		#var coll = $CollisionShape2D as CollisionShape2D
		await anim.animation_finished
		self.queue_free()
		Game.Gold +=5
		#Utils.saveGame()

func _on_area_check_touch_body_entered(body):
	if body.name == "Player":
		#var player = $"../../Player/Player" as CharacterBody2D
		#print("伤害")
		Game.playerHP -= 30
		Utils.saveGame()
